package de.mindshareprojects.datawarehouse.client;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.mindshareprojects.datawarehouse.shared.Advertiser;
import de.mindshareprojects.datawarehouse.shared.Campaign;
import de.mindshareprojects.datawarehouse.shared.CampaignList;


public class CampaignIds {
	
	private final static DataServiceAsync dataService = GWT.create(DataService.class);
	public static String message = new String();
	public static String campaignIdsXml = new String();
	
	public static Boolean reverseOrder = false;
	public static String lastSort = "";
	
	// GUI elements
	private static VerticalPanel vpCampaignIdContent = new VerticalPanel();
	private static FlexTable ftDataContent = new FlexTable();
	private static TextBox tbCampaignName = new TextBox();
	public static ListBox lbAdvertiser = new ListBox();
	private static HTML lastCampaign = new HTML();
	private static Button bCreateCampaign = new Button("Create");
	private static Button bShowCampaigns = new Button("Show campaigns");
	private static Button bShowAdvertisers = new Button("Show advertisers");

	private static TextBox tbAdvertiserName = new TextBox();
	private static TextBox tbAdvertiserForeignKey = new TextBox();
	private static TextBox tbAdvertiserGroupKey = new TextBox();
	private static TextBox tbAdvertiserGroupName = new TextBox();
	private static CheckBox cbWebAnalyticsEnabled = new CheckBox();
	private static Button bCreateAdvertiser = new Button("Create");
	
	private static CampaignList campaignList = null;
	
	
	public static VerticalPanel campaignIdPanel() {
		
		int row = 0;
		int column = 0;

		vpCampaignIdContent.add(ftDataContent);
		
		if(DataWarehouse.loginInfo.isAdmin() == true){
			
			ftDataContent.setWidget(row, column, new Label("Create advertiser"));
			((Label)ftDataContent.getWidget(row, column)).addStyleName("simpleHeader");
			row++;
			ftDataContent.setWidget(row, column, new Label("Advertiser name"));
			ftDataContent.setWidget(row, column + 1, tbAdvertiserName);
			row++;
			ftDataContent.setWidget(row, column, new Label("Foreign ID"));
			ftDataContent.setWidget(row, column + 1, tbAdvertiserForeignKey);
			row++;
			ftDataContent.setWidget(row, column, new Label("Use Web Analytics"));
			ftDataContent.setWidget(row, column + 1, cbWebAnalyticsEnabled);
			row++;
			ftDataContent.setWidget(row, column, new Label("Web Analytics Group"));
			ftDataContent.setWidget(row, column + 1, tbAdvertiserGroupName);
			row++;
			ftDataContent.setWidget(row, column, new Label("Web Analytics Group Key"));
			ftDataContent.setWidget(row, column + 1, tbAdvertiserGroupKey);
			row++;
			ftDataContent.setWidget(row, column, bCreateAdvertiser);
			
			row++;
		}
		ftDataContent.setWidget(row, column, new Label("Create campaign"));
		((Label)ftDataContent.getWidget(row, column)).addStyleName("simpleHeader");
		row++;
		ftDataContent.setWidget(row, column, new Label("Campaign name:"));
		ftDataContent.setWidget(row, column + 1, tbCampaignName);
		row++;
		ftDataContent.setWidget(row, column, new Label("Advertiser"));
		ftDataContent.setWidget(row, column + 1, lbAdvertiser);
		row++;
		ftDataContent.setWidget(row, column, bCreateCampaign);
		row++;
		ftDataContent.setWidget(row, column, lastCampaign);

		row++;
		row++;
		ftDataContent.setWidget(row, column, bShowCampaigns);
		column++;
		ftDataContent.setWidget(row, column, bShowAdvertisers);
		
		vpCampaignIdContent.add(new HTML("<br/><br/>"));
		
		
		/**
		 * add click handler to button: "Create" campaign
		 * get parameter values from from fields and hand them to <code>createCampaign</code>
		 */
		bCreateCampaign.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(DataWarehouse.lbCountrySelection.getValue(DataWarehouse.lbCountrySelection.getSelectedIndex()) == "--"){
					Window.alert("No country selected!");
					return;
				}
				else if(tbCampaignName.getText() == ""){
					Window.alert("Please enter a valid campaign name!");
					return;
				} else if (lbAdvertiser.getValue(lbAdvertiser.getSelectedIndex()) == "--") {
					Window.alert("No advertiser selected!");
					return;
				}
				createCampaign(DataWarehouse.lbCountrySelection.getValue(DataWarehouse.lbCountrySelection.getSelectedIndex()), tbCampaignName.getText(), Long.parseLong(lbAdvertiser.getValue(lbAdvertiser.getSelectedIndex())), lbAdvertiser.getItemText(lbAdvertiser.getSelectedIndex()), DataWarehouse.loginInfo.getEmailAddress());
				
				switchSortOrder("byId");
				showCampaigns("byId", reverseOrder);
				
			}
		});
		
		bCreateAdvertiser.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				Advertiser advertiserToSave = new Advertiser();
				advertiserToSave.setAdvertiserName(tbAdvertiserName.getText());
				advertiserToSave.setCountry(DataWarehouse.selectedCountry);
				advertiserToSave.setUserName(DataWarehouse.loginInfo.getEmailAddress());
				advertiserToSave.setWebAnalytics(cbWebAnalyticsEnabled.getValue());
				advertiserToSave.setAdvertiserGroupName(tbAdvertiserGroupName.getText());
				advertiserToSave.setAdvertiserGroupKey(Long.parseLong(tbAdvertiserGroupKey.getText()));
				createAdvertiser(advertiserToSave);
			}
		});
		
		bShowCampaigns.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				getCampaigns();
				
			}
		});
		
		bShowAdvertisers.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				
			}
		});
		
		return vpCampaignIdContent;
	}
	
	/**
	 * creates Campaign object and dispatches it via RPC to server
	 * @param campaignName
	 * @param advertiserId
	 * @param advertiserName
	 * @param userName
	 * 
	 * @return void
	 */
	private static void createCampaign (String country, String campaignName, Long advertiserId, String advertiserName, String userName) {
		
		Campaign campaign = new Campaign();
		campaign.setCampaignName(campaignName);
		campaign.setAdvertiserId(advertiserId);
		campaign.setAdvertiserName(advertiserName);
		campaign.setCountry(country);
		
		dataService.createCampaign(campaign, new AsyncCallback<Campaign>() {
			
			@Override
			public void onSuccess(Campaign serverResponse) {
				// TODO Auto-generated method stub
				DataWarehouse.log("Campaign created: " + serverResponse.getKey() + " " + serverResponse.getCampaignName() + " for " + serverResponse.getAdvertiserName() + "[" + serverResponse.getAdvertiserId() + "]");
				lastCampaign.setHTML("Campaign <b>[" + serverResponse.getKey() + "]</b> created: <br>" + serverResponse.getCampaignName());
			}
			
			@Override
			public void onFailure(Throwable caught) {
				
				DataWarehouse.log("RPC failure creating campaign.");
			}
		});
	}
	
	/**
	 * creates Advertiser object and dispatches it via RPC to server
	 * @param Advertiser The advertiser to save
	 */
	private static void createAdvertiser (Advertiser advertiserToSave) {
		
		dataService.createAdvertiser(advertiserToSave, new AsyncCallback<Advertiser>() {
			
			@Override
			public void onSuccess(Advertiser serverResponse) {
				DataWarehouse.log("Advertiser created: " + serverResponse.getAdvertiserName() + " [" + serverResponse.getKey() + "]");
				lbAdvertiser.addItem(serverResponse.getAdvertiserName(), serverResponse.getKey().toString());
				DataWarehouse.lbAdvertiser.addItem(serverResponse.getAdvertiserName(), serverResponse.getKey().toString());
			}
			
			@Override
			public void onFailure(Throwable caught) {
				
				DataWarehouse.log("RPC failure while creating advertiser.");
			}
		});
	}
	public static void getCampaigns(){
		
		dataService.getCampaignsByCountry(DataWarehouse.selectedCountry, new AsyncCallback<ArrayList<Campaign>>() {
			
			@Override
			public void onFailure(Throwable caught) {
				DataWarehouse.log("RPC failure while getting campaign list.");
				
			}
			
			@Override
			public void onSuccess(ArrayList<Campaign> result) {
				campaignList = new CampaignList(result);
				showCampaigns("key", reverseOrder);
			}
		});
	}
	
	/**
	 * 
	 * @param sorting String "byName", "byId", "none"
	 * @param reverse Boolean
	 * 
	 */
	private static void showCampaigns(final String sorting, final Boolean reverse){
		
				
				DataWarehouse.ftShowData.clear();
				campaignList.sort(sorting);
				if(reverse == true) campaignList.reverse();
				
				int column = 0;
				DataWarehouse.ftShowData.setWidget(0, column, new Label("ID"));
				((Label)DataWarehouse.ftShowData.getWidget(0, column)).addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						switchSortOrder("key");
						showCampaigns("key", reverseOrder);
						
					}
				});
				column++;
				DataWarehouse.ftShowData.setWidget(0, column, new Label("Campaign"));
				((Label)DataWarehouse.ftShowData.getWidget(0, column)).addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						switchSortOrder("name");
						showCampaigns("name", reverseOrder);
						
					}
				});
				column++;
				DataWarehouse.ftShowData.setWidget(0, column, new Label("Advertiser"));
				((Label)DataWarehouse.ftShowData.getWidget(0, column)).addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						switchSortOrder("advertiser");
						showCampaigns("advertiser", reverseOrder);
						
					}
				});
				
				DataWarehouse.ftShowData.getRowFormatter().addStyleName(0, "FlexTable-Header");
				DataWarehouse.ftShowData.addStyleName("table");
				
				int i = 1;
				for (Campaign c: campaignList.getItems()) {
					DataWarehouse.ftShowData.setWidget(i, 0, new Label(c.getKey().toString()));
					DataWarehouse.ftShowData.setWidget(i, 1, new Label(c.getCampaignName()));
					DataWarehouse.ftShowData.setWidget(i, 2, new Label(c.getAdvertiserName() + " [" + c.getAdvertiserId() + "]"));
					i++;
				}
				
	}
	
	
	
	
	
	/**
	 * Handles the sort order of lists
	 * @param sortCriterion
	 */
	public static void switchSortOrder(String sortCriterion){
		// if sort is executed for first time, apply ascending order
		if(!sortCriterion.equalsIgnoreCase(lastSort)) reverseOrder = false;
		// if sort is exwecuted on same column again, switch order
		else if(sortCriterion.equalsIgnoreCase(lastSort)) reverseOrder = !reverseOrder;
		// store sort order criterion in public variable
		lastSort = sortCriterion;
		
	}
	
}

